const { Server, Socket } = require("socket.io");
const { messageModel } = require("./model");

const socketio = {};

socketio.getSocketio = function (server) {
  let io = new Server(server, { cors: true });
  io.sockets.on("connection", function (socket) {
    socket.on("joinRoom", (room) => {
      socket.join(room);
      console.log(`User ${socket.id} joined room ${room}`);
    });
    socket.on("message", async (data) => {
      console.log(data.img,1111);
      const newMessage = new messageModel({
        content: data.content,
        sender: data.sender,
        channel: data.channel,
        createtime: data.createtime,
        img:data.img
      });
      await newMessage.save();
      io.to(data.channel).emit("messageResponse", newMessage);
    });
    socket.on('offer', (offer) => {
      socket.to(otherUser).emit('offer', offer);
    });

    socket.on('answer', (answer) => {
      socket.to(otherUser).emit('answer', answer);
    });

    socket.on('ice', (ice) => {
      socket.to(otherUser).emit('ice', ice);
    });

  });
};

module.exports = socketio;
